﻿using Chire.ChireInter.Students;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace Chire.ChireInter.Event_calendar
{
    /// <summary>
    /// Event_Add 的摘要说明
    /// </summary>
    public class Event_Add : IHttpHandler
    {
        HttpContext contextWithBase;
        string name = "";
        string datetime = "";
        string classId = "";
        string type = "";   // 1 仅1次 // 2. 轮回

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            contextWithBase = context;
            analysisInfo();
        }

        #region 验证信息
        public void analysisInfo()
        {
            if (contextWithBase.Request.Form.AllKeys.Contains("name"))
            {
                name = contextWithBase.Request.Form["name"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("datetime"))
            {
                datetime = contextWithBase.Request.Form["datetime"];
            }
            if (contextWithBase.Request.Form.AllKeys.Contains("classId"))
            {
                classId = contextWithBase.Request.Form["classId"];
            }

            insertIntoEvent();
        }
        #endregion

        #region 插入数据
        public void insertIntoEvent()
        {
            Event_Action eventAction = new Event_Action();
            string eventId = eventAction.addEventManager(name, datetime, classId,EventType.EventTypeOther);

            // 根据班级获取所有学生
            Student_Action studentAction = new Student_Action();
            List<Student_Model> studentList = studentAction.getAllStudentWithClassId(classId);
            // 根据学生将事件按数据插入到表中
            for (int i = 0; i < studentList.Count; i++) {
                Student_Model student = studentList[i];
                eventAction.addEventWithStudent(student.id, eventId);
            }
            successManager();
        }
        #endregion

        #region 成功方法
        public void successManager()
        {
            OUTEvent_Model out_base_setting = new OUTEvent_Model();
            out_base_setting.errCode = "200";
            out_base_setting.errMsg = "接口请求成功";
            out_base_setting.data = null;


            JsonSerializer serializer = new JsonSerializer();
            StringWriter sw = new StringWriter();
            serializer.Serialize(new JsonTextWriter(sw), out_base_setting);
            string info = sw.GetStringBuilder().ToString();
            contextWithBase.Response.Write(sw.GetStringBuilder().ToString());
        }
        #endregion

        #region 其他
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        #endregion

    }
}